package com.diaohaiwen.framework.db;

import com.diaohaiwen.common.obj.cache.RequestCache;
import com.diaohaiwen.framework.db.obj.BaseCUModel;
import com.diaohaiwen.framework.db.obj.BaseCModel;
import com.mybatisflex.annotation.InsertListener;
import com.mybatisflex.annotation.UpdateListener;

import java.time.LocalDateTime;

/**
 * @author 刁海文
 * @since 2023/7/19 15:01
 * @Remark
 */
public class GlobalListener implements UpdateListener, InsertListener {

    @Override
    public void onUpdate(Object entity) {
        if (entity instanceof BaseCUModel base) {
            base.setUpdatedBy(RequestCache.getLoginUser().getName());
            base.setUpdatedTime(LocalDateTime.now());
        }
    }

    @Override
    public void onInsert(Object entity) {
        if (entity instanceof BaseCUModel base) {
            base.setUpdatedBy(RequestCache.getLoginUser().getName());
            base.setUpdatedTime(LocalDateTime.now());
            base.setCreatedBy(RequestCache.getLoginUser().getName());
            base.setCreatedTime(LocalDateTime.now());
        }

        if (entity instanceof BaseCModel log) {
            log.setCreatedTime(LocalDateTime.now());
        }
    }
}
